package red.mlz.app;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import red.mlz.module.module.smslog.entity.SmsLog;
import red.mlz.module.module.smslog.service.SmsLogService;
import red.mlz.module.module.smstask.entity.SmsTask;
import red.mlz.module.module.smstask.service.SmsTaskService;

import java.util.List;

@Component
public class SmsTaskScheduler {

    @Autowired
    private SmsTaskService smsTaskService;
    @Autowired
    private SmsLogService smsLogService;

    @Scheduled(fixedRate = 60000) // 每60秒执行一次
    public void scheduleSmsTask() {
        List<SmsTask> tasks = smsTaskService.findByStatus(0);

        tasks.forEach(smsTask -> {
            try {
                SendSmsResponse response = smsLogService.sendSync(smsTask.getPhone(),
                        "阿里云短信测试",
                        "SMS_154950909",
                        "{\"code\":\""+smsTask.getContent()+"\"}"
                );
                //更新任务状态
                smsTaskService.updateStatus(smsTask.getId(), 1); // 假设1表示成功

                //记录日志
                int timestamp = (int) (System.currentTimeMillis() / 1000);
                SmsLog log = new SmsLog();
                log.setPhone(smsTask.getPhone());
                log.setContent(smsTask.getContent());
                log.setResult(response.getCode() + ":" + response.getMessage());
                log.setSendTime(timestamp);
                log.setCreateTime(timestamp);
                log.setUpdateTime(timestamp);
                log.setIsDeleted(0);
                smsLogService.insert(log);
            } catch (ClientException e) {
                smsTaskService.updateStatus(smsTask.getId(), 2);
            }
        });
    }
}
